class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            name: '',
            id: 0,
            counts: [],
            start: 1,
            pagesize: 15,
            name: "",
            phone: "",
            fetching: !1,
            keyword: "",
            userhtml: [],
            userlist: [],
            starttime: "",
            endtime: "",
            freight: 0,
            username: "",
            password: "",
            address: "",
            longitude: "", latitude: "",
            userid: "",
            lat: "",
            lng: "",
            province: "",
            city: "",
            district: "",
            // county:"",
            street: "",
            isrecommend:"0",
        };
    }

    submit() {
        var { name, phone, userid, lat, lng, province, city, district, street, starttime, endtime, freight, username, password, id,isrecommend } = this.state,
            that = this, err = '';

        if (street == "") err = "请输入详细的店铺地址"
        if (province == "" || city == "") err = "获取不到店铺所在城市"
        if (lat == "" || lng == "") err = "请定位店铺位置"
        if (id <= 0) {
            if (password == "") err = "请输入店铺后台管理的登录密码"
        }
        if (username == "") err = "请输入店铺后台管理的登录账号"
        if (starttime == "" || endtime == "") err = "请选择完整的营业时间"
        if (phone == "") err = "请输入店铺电话"
        if (name == "") err = "请输入店铺名称"
        if (err.length > 0) {
            alert(err);
            return
        }


        this.setState({ showloading: 'ON' })
        password = md5(password + Constant.SALT);
        if (userid == "") {
            userid = 0
        }
        var data = { name, phone, userid, lat, lng, province, city, county: district, street, starttime, endtime, 
            freight: Math.round(freight * 100), username, password,isrecommend, }
        if (this.state.id > 0) data['id'] = this.state.id;
        console.log(data, 'data')
        Shopaoe(data, res => {
            this.setState({ isloading: !1 })
            if (res.issuccess == 1) {
                alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                window.location.href = "./shop.html";
            } else {
                that.setState({ showloading: '' })
                alert(res.msg)
            }
        })

    }

    componentDidMount() {
        this.setState({ showloading: '' })
        let that = this, { } = that.state;
        moment.locale()
        // moment.locale("zh-cn")
        let id = GetQueryString('id')
        // console.log(id, 'iddididid');
        that.initQQMap()
        if (id != 'null' && id) {
            that.setState({ id }, () => {
                that.getuserlist()
                that.freshlist()
            })
        } else {
            that.getuserlist()
            that.setState({ showloading: '' })
        }

    }

    freshlist() {
        let { id } = this.state, that = this;
        Shopsetgetdetail(id, res => {
            this.setState({ showloading: '' })
            if (res.issuccess == 1) {
                let { } = this.state,
                    { name, phone, userid, lat, lng, province, city, county, street, starttime, endtime, freight, username, isrecommend, } = res.data
                // 清空上一次搜索结果
                Array.from(this.markers).forEach(marker => {
                    marker.setMap(null);
                });
                // //腾讯地图的根据经纬度度定位
                var coord = new qq.maps.LatLng(lat, lng);
                this.searchService.getAddress(coord);
                that.setState({ name, phone, userid, lat, lng, province, city, district: county, street, starttime, endtime, freight: freight / 100.00, username,isrecommend })
            }
        })
    }
    getuserlist() {
        let { keyword, id } = this.state, that = this, userhtml = []
        getlistbysearch({ keyword, shopid: id }, res => {
            if (res.issuccess == 1) {
                if (res.list.length > 0) {
                    res.list.forEach(x => {
                        userhtml.push(
                            <antd.Select.Option value={x.id}>{"ID:" + x.id + ",昵称:" + x.nickName} </antd.Select.Option>
                        )
                    })
                }
                that.setState({ fetching: !1, userhtml, userlist: res.list })
            }
        })
    }

    inputchange(prop, e) {
        this.setState({ [prop]: e.target.value })
    }
    search() {
        let that = this
        that.setState({ showloading: 'ON' }, () => {
            that.getuserlist()
        })
    }
    inputchange1() {
        let {isrecommend}=this.state
        isrecommend=isrecommend=="1"?"0":"1"
        this.setState({isrecommend})
    }
    inputchange3(prop, e) {
        this.setState({ [prop]: e })
    }
    onChangeSelect(e) {
        let { userlist } = this.state, that = this
        console.log(e, 'eeee');
        if (e) {
            if (userlist.length > 0) {
                userlist.forEach(x => {
                    if (x.id == e) {
                        that.setState({ userid: e, keyword: "ID:" + x.id + ",昵称:" + x.nickName })
                    }
                })
            }
        } else {
            that.setState({ userid: "", keyword: "" }, () => {
                that.getuserlist()
            })
        }

    }
    timechange(prop, dates, dateString) {
        let that = this
        if (dates == "null" || dates == null) {
            this.setState({ [prop]: "" })
        } else {
            if (prop == "starttime") {
                let { endtime } = that.state
                if (endtime != "") {
                    if (endtime <= dateString) {
                        that.setState({ [prop]: "" })
                        alert("结束时间必须大于开始时间")
                        return;
                    }
                }
            } else {
                let { starttime } = that.state
                if (starttime != "") {
                    if (dateString <= starttime) {
                        that.setState({ [prop]: "" })
                        alert("结束时间必须大于开始时间")
                        return;
                    }
                }
            }
            that.setState({ [prop]: dateString })
        }
    }


    initQQMap = () => {
        let that = this
        //设置中心坐标
        let tarLat = 39.90736606309809;
        let tarLng = 116.39774322509766;
        //初始化地图
        var qq = window.qq;

        // 初始化经纬度，最开始的点
        let myLatlng = new qq.maps.LatLng(tarLat, tarLng);
        // 设置地图属性
        let myOptions = {
            zoom: 10,
            center: myLatlng,
            mapTypeId: qq.maps.MapTypeId.ROADMAP,
        };
        // 创建地图，绑定dom
        this.map = new qq.maps.Map(
            document.getElementById('map'),
            myOptions,
        );

        // 现实已经存在的点
        let markerlast = new qq.maps.Marker({
            position: myLatlng,
            map: this.map,
        });




        // 调用检索
        let latlngBounds = new qq.maps.LatLngBounds();
        let searchService = [];//调用百度地图的搜索服务
        let LatLngService = [];//调用百度地图的经纬度获取地址
        let markers = [];//用户搜索后显示的点的集合

        var callbacks = {
            complete: function (results) {
                console.log(results, 'resultsresults');
                that.map.setCenter(results.detail.location);
                console.log(results.detail.location, 'result.detail.location');
                // var marker = new qq.maps.Marker({
                //     map:map,
                //     position: result.detail.location
                // });
                latlngBounds.extend(results.detail.location);
                let marker = new qq.maps.Marker({
                    map: that.map,
                    position: results.detail.location,
                });
                marker.setTitle(1);
                markers.push(marker);
                // Array.from(this.markers).forEach(marker => {
                //     marker.setMap(null);
                // });
                let province = results.detail.addressComponents.province, city = results.detail.addressComponents.city, district = results.detail.addressComponents.district,
                    street = results.detail.addressComponents.street
                if (province == "") {
                    province = city
                }
                that.setState({
                    lat: results.detail.location.lat, lng: results.detail.location.lng,
                    city, province, district, street
                })
                that.map.fitBounds(latlngBounds);



            },
        }


        var callbacks1 = {
            complete: function (results) {
                console.log(results, 'resultsresults');
                let province = results.detail.addressComponents.province, city = results.detail.addressComponents.city, district = results.detail.addressComponents.district,
                    street = results.detail.addressComponents.street
                if (province == "") {
                    province = city
                }
                that.setState({ city, province, district, street })
            },
        }
        searchService = new qq.maps.Geocoder(callbacks);
        LatLngService = new qq.maps.Geocoder(callbacks1);


        // 将服务注册到this中，方便搜索方法调用
        this.searchService = searchService;
        this.LatLngService = LatLngService;
        this.markers = markers;
        // 鼠标点击监听
        qq.maps.event.addListener(
            this.map,
            'click',
            event => {
                // console.log(event, 'addListener--eventevent');
                // 清除初始化位置
                markerlast.position = event.latLng;
                markerlast.setMap(null);
                // 获取经纬度位置
                let lat = event.latLng.getLat();
                let lng = event.latLng.getLng();
                // console.log(lat, 'latlat');
                // console.log(lng, 'lng');
                // 赋值至文本框内
                // getssq({ lat, lng }, res => {
                //     if (res.issuccess == 1) {
                //         // console.log(res.result, 'res.result');
                //         that.setState({ address: res.result.address, city: res.result.address_component.city, province: res.result.address_component.province, district: res.result.address_component.district, })
                //     }
                // })
                var coord = new qq.maps.LatLng(lat, lng);
                LatLngService.getAddress(coord);

                that.setState({ lat: lat, lng: lng })
                // this.props.form.setFieldsValue({ lat: lat, lng: lng });
                // 绘制点击的点
                let marker = new qq.maps.Marker({
                    position: event.latLng,
                    map: this.map,
                });
                // 添加监听事件   获取鼠标单击事件
                qq.maps.event.addListener(this.map, 'click', function (event) {
                    marker.setMap(null);
                });
                // 清空上一次搜索结果
                Array.from(this.markers).forEach(marker => {
                    marker.setMap(null);
                });
            }
        );
        // });
    }

    location() {
        //获取文本框输入的值
        let { address } = this.state
        if (address == '') {
            alert("请输入地址")
            return;
        }
        // 清空上一次搜索结果
        Array.from(this.markers).forEach(marker => {
            marker.setMap(null);
        });
        //调用腾讯地图的搜索功能
        this.searchService.getLocation(address);
    }
    toback() {
        window.location.href = "./shop.html";
    }


    render() {
        let { name, phone, fetching, keyword, userhtml, starttime, endtime, freight, username, password, address, province, city, district, street, lng, lat, id,
            userid, isrecommend} = this.state;
        return (
            <div className="breadLinebox">
                <Loading hidden={this.state.showloading != 'ON'} />


                <div className='content_wrap panel-default content_wrap'>
                    <div className="breadLine">

                        <div className="flexitems">
                            <div className="img">
                                <span onClick={this.toback.bind(this)} style={{ cursor: 'pointer' }}>店铺管理</span> <span className="fenge">{"/"}</span> {this.state.id > 0 ? "编辑" : "新建"}店铺
                            </div>

                        </div>
                    </div>
                    <div className="contentbox form">
                        <div className="formcontent">
                            <div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>店铺名称：</span>
                                    </div>
                                    <div>
                                        <antd.Input placeholder="请输入" allowClear value={name} onChange={this.inputchange.bind(this, 'name')} className="input" />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>店铺电话：</span>
                                    </div>
                                    <div><antd.Input placeholder="请输入" allowClear value={phone} onChange={this.inputchange.bind(this, 'phone')} className="input" /></div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>绑定用户：</span>
                                    </div>
                                    <div className="disflexwrap">
                                        <antd.Select value={userid} allowClear style={{ width: "150px" }} placeholder="请选择用户" onChange={this.onChangeSelect.bind(this)} >
                                            {userhtml}
                                        </antd.Select>
                                        <antd.Input placeholder="请输入用户昵称" allowClear value={keyword} style={{ width: "100px", marginLeft: "10px" }} onChange={this.inputchange.bind(this, 'keyword')} className="input" />
                                        <p className="add" onClick={this.search.bind(this)}>搜索</p>

                                    </div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>营业时间：</span>
                                    </div>
                                    <div>
                                        {/* locale={antd.zh_CN}  */}
                                        <antd.TimePicker onChange={this.timechange.bind(this, "starttime")} value={starttime == "" ? null : moment(starttime, "hh:mm:ss")} style={{ width: "150px" }} placeholder="开始营业时间" />
                                        <span className="marginlr">-</span>
                                        <antd.TimePicker onChange={this.timechange.bind(this, "endtime")} value={endtime == "" ? null : moment(endtime, "hh:mm:ss")} style={{ width: "150px" }} placeholder="结束营业时间" />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>配送费：</span>
                                    </div>
                                    <div>
                                        <antd.InputNumber min={0} precision={2} style={{ width: "300px" }} value={freight} onChange={this.inputchange3.bind(this, 'freight')} />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>是否推荐：</span>
                                    </div>
                                    <div>
                                        <antd.Switch checked={isrecommend == "1" ? true : false} onChange={this.inputchange1.bind(this)} />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>登录账号：</span>
                                    </div>
                                    <div>
                                        <antd.Input placeholder="请输入" allowClear value={username} onChange={this.inputchange.bind(this, 'username')} className="input" />

                                    </div>
                                </div>
                                <div className="input-group" style={{ display: id > 0 ? "none" : "" }}>
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>登录密码：</span>
                                    </div>
                                    <div>
                                        <antd.Input placeholder="请输入" allowClear value={password} onChange={this.inputchange.bind(this, 'password')} className="input" />
                                    </div>
                                </div>
                                <div className="input-group">
                                    <div className="parametermane">
                                        <span>店铺地址：</span>
                                    </div>
                                    <div className="disflex">
                                        <antd.Input placeholder="请输入店铺地址后定位" allowClear value={address} onChange={this.inputchange.bind(this, 'address')} className="input" />
                                        <p className="add" onClick={this.location.bind(this)}>定位</p>
                                    </div>
                                </div>
                                <div className="disflexwrap">
                                    <div className="input-group disflex w500">
                                        <div className="parametermane">
                                            <span className="red mr5">*</span>
                                            <span>经纬度：</span>
                                        </div>
                                        <div className="disflex" style={{ display: lng == "" ? "none" : "" }}>
                                            {lng + "," + lat}
                                        </div>
                                    </div>
                                    <div className="input-group disflex w350">
                                        <div className="parametermane">
                                            <span className="red mr5">*</span>
                                            <span>省市区：</span>
                                        </div>
                                        <div className="disflex" style={{ display: province == "" ? "none" : "" }}>
                                            {province + "," + city + "," + district}
                                        </div>
                                    </div>

                                </div>
                                <div className="input-group" style={{ display: province == "" ? "none" : "" }}>
                                    <div className="parametermane">
                                        <span className="red mr5">*</span>
                                        <span>详细地址：</span>
                                    </div>
                                    <div className="disflex">
                                        <antd.Input placeholder="请输入店铺的详细地址" allowClear value={street} onChange={this.inputchange.bind(this, 'street')} className="input" />
                                    </div>
                                </div>

                                <div id="map" className="map" ></div>
                            </div>

                        </div>
                        <div className="submitbox">
                            <button type="button" onClick={this.submit.bind(this)} className="submitbutton">提交</button>
                            <button type="button" onClick={this.toback.bind(this)} className="submitbutton" style={{ marginLeft: '100' }}>返回</button>
                        </div>
                    </div>
                </div>
            </div>


        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='shop' height='shop' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)